package com.connect.nio;

import com.dto.cnc.CncDTO;
import com.safe.CheckCNCImpl;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldPrepender;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableAsync;

import java.net.InetSocketAddress;

@Slf4j
@NoArgsConstructor
@EnableAsync
public class FastEcho {
    String host = CncDTO.getCnc_ip();
    int port = Integer.parseInt(CncDTO.getCnc_port());

//    public static EventLoopGroup group;

    public String str;
    //worker负责读写数据

    /*配置信息Socket*/

    public boolean doFastEcho(EventLoopGroup group ,String cncServerHost, int cncServerPort) throws InterruptedException {


        try {

            //辅助启动类
            Bootstrap bootstrap = new Bootstrap();

            //设置线程池
            bootstrap.group(group);

            //设置socket工厂
            bootstrap.channel(NioSocketChannel.class);
            // 连接超时时间
            bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
            // 心跳
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            // 配置Channel参数，nodelay没有延迟，true就代表禁用Nagle算法，减小传输延迟。
            bootstrap.option(ChannelOption.TCP_NODELAY, true);
            /*立即释放*/
            bootstrap.option(ChannelOption.SO_REUSEADDR, true);

            //设置管道
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    //获取管道
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast(new LengthFieldPrepender(8));
                   // pipeline.addLast(new IdleStateHandler(64, 64, 128, TimeUnit.MILLISECONDS));
                    pipeline.addLast(new CheckCNCImpl());
                }
            });

            //发起异步连接
            ChannelFuture future = bootstrap.connect(new InetSocketAddress(cncServerHost, cncServerPort)).sync().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        log.error("连接远程地址错误" + future.cause());
                        future.channel().close();
//                        future.channel().closeFuture();
                    }
                }
            });

            return true;
        } catch (Throwable e) {
            log.error("通信错误：" + e.toString());

            return false;
        } finally {
            //优雅的退出，释放NIO线程组
            group.shutdownGracefully();
        }

    }





}
